package ru.urfc.portal.model;

import java.math.BigInteger;
import java.security.MessageDigest;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.Transient;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

import ru.urfc.portal.exceptions.InternalException;
import ru.urfc.portal.ui.client.Constants;

@Entity
@XmlRootElement(name = Constants.ASSOCIATION_KEY)
public class AssociationKey extends SysObject {

	@Transient
	private String key;
	@JoinColumn(nullable = false, unique = true)
	private Client client;
	@Column(nullable = false, unique = true, length=64)
	private String hash;

	public AssociationKey() {
	}

	public AssociationKey(String key, Client client) {
		this.key = key;
		this.client = client;
		this.hash = evaluateHash(key);
	}

	public static class HashGenerationException extends InternalException {

		public HashGenerationException(Throwable cause, String message) {
			super(cause, message);
		}
		
	}
	
	public String evaluateHash() {
		return evaluateHash(key);
	}
	
	String evaluateHash(String key) {
		key = key == null? "": key.replaceAll("[-\\s]+", "");
		try {
			MessageDigest digester = MessageDigest.getInstance("SHA-256");
			digester.reset();
			digester.update(key.getBytes("UTF-8"));
			return new BigInteger(1, digester.digest()).toString(16);
		} catch (Exception e) {
			throw new HashGenerationException(e, "Can't generate hash");
		}
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}
	
	@XmlTransient
	public String getHash() {
		return hash;
	}

	public void setHash(String hash) {
		this.hash = hash;
	}
	
	@XmlTransient
	public Client getClient() {
		return client;
	}
	
}
